package top.mollysu.sell.controller;

import com.lly835.bestpay.model.PayResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import top.mollysu.sell.dto.OrderDTO;
import top.mollysu.sell.exception.SellException;
import top.mollysu.sell.service.OrderService;
import top.mollysu.sell.service.PayService;

import java.util.Map;

@Controller
@Log4j2
public class PayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayService payService;

    @GetMapping("/pay")
    public ModelAndView pay(@RequestParam("openid") String openid,
                            @RequestParam("orderId") String orderId,
                            @RequestParam("returnUrl") String returnUrl,
                            Map<String, Object> map){
        log.info("openid={}", openid);
//        String orderId = "1519929590868";
        //1. 查询订单
        OrderDTO orderDTO = new OrderDTO();
        try {
            orderDTO = orderService.findOne(orderId);
        } catch (SellException e) {
            log.error("【查不到订单】e={}", e.getMessage());
        }

        //发起支付
        orderDTO.setBuyerOpenid(openid);
        PayResponse response = payService.create(orderDTO);
        map.put("response", response);
        map.put("returnUrl", returnUrl);
        return new ModelAndView("pay/create.btl", map);

    }

}
